package com.zhongying.jf.util.sftp;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;

public class SFTPUtil {

    private ChannelSftp sftp = null;

    /**
     * connect server via sftp
     */
    public void connect(String addr,int port,String username,String password) {
        try {
            if(sftp != null){
                System.out.println("sftp is not null");
            }
            JSch jsch = new JSch();
            jsch.getSession(username, addr, port);
            Session sshSession = jsch.getSession(username, addr, port);
            System.out.println("Session created.");
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect(30000);
            System.out.println("Session connected.");
            System.out.println("Opening Channel.");
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
             sftp = (ChannelSftp) channel;
            System.out.println("Connected to " + addr + ".");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void download() {
        // TODO Auto-generated method stub

    }

    /**
     * Disconnect with server
     */
    public void disconnect() {
        if(this.sftp != null){
            if(this.sftp.isConnected()){
                this.sftp.disconnect();
            }else if(this.sftp.isClosed()){
                System.out.println("sftp is closed already");
            }
        }

    }


    private void download(String directory, String downloadFile,String saveFile, ChannelSftp sftp) {
        try {
            sftp.cd(directory);
            File file = new File(saveFile);
            sftp.get(downloadFile, new FileOutputStream(file));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *          上传文件
     * @param file      本地文件
     * @param parenetPath   服务器路径，只能是当前用户连接下的路径
     * @throws Exception
     */
    public void upload(File file,String parenetPath)throws Exception{
        if(!StringUtils.isEmpty(parenetPath)){
            sftp.cd(parenetPath);
        }
        if(file.isDirectory()){
            String fileName = file.getName();
            sftp.mkdir(fileName);
            sftp.cd(fileName);
            parenetPath = parenetPath + "/" +  file.getName();
             String[] files=file.list();
            for(int i =0;i<files.length;i++){
                //创建下一级文件
                File file1 =new File(file.getPath()+ File.separator +files[i]);
                if(file1.isDirectory()){
                    //递归
                    upload(file1,parenetPath);
                    sftp.cd(parenetPath);
                }else{
                    File file2 =new File(file.getPath()+"\\"+files[i]);
                    FileInputStream input = new FileInputStream(file2);
                    sftp.put(input,file2.getName());
                 //   input.close();
                }
                }
        }else{
                File file2=new File(file.getPath());
                FileInputStream input = new FileInputStream(file2);
                sftp.put(input,file2.getName());
              //  input.close();
       }
}


    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        SFTPUtil ftp= new SFTPUtil();
        ftp.connect("192.168.1.244",22,"lhj","haijie");
        ftp.upload(new File("/jade/p2p/data/file/MB.rar"),"");
        ftp.disconnect();
        System.exit(0);
    }


}
